﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Wisdom.Core;

namespace Wisdom.Web.Mvc
{
    internal class ControllerActionInvokerHelper
    {
        public static void Inject(IServiceInjector container, FilterInfo filters)
        {
            ICollection<object> injectedFilters = new HashSet<object>();

            Inject(container, injectedFilters, filters.AuthorizationFilters);
            Inject(container, injectedFilters, filters.ActionFilters);
            Inject(container, injectedFilters, filters.ResultFilters);
            Inject(container, injectedFilters, filters.ExceptionFilters);
        }

        #region Private Methods

        private static void Inject<TFilter>(IServiceInjector container, ICollection<object> injectedFilters, IEnumerable<TFilter> filters)
            where TFilter : class
        {
            foreach (TFilter filter in
                    filters.Where(filter => !injectedFilters.Contains(filter) && IsFilterAttribute(filter)))
            {
                container.Inject(filter);
                injectedFilters.Add(filter);
            }
        }

        private static bool IsFilterAttribute<TFilter>(TFilter filter)
        {
            return KnownTypes.FilterType.IsInstanceOfType(filter);
        }

        #endregion
    }
}